package internationalenergytradingplatform.service.Impl;

import internationalenergytradingplatform.context.BaseContext;
import internationalenergytradingplatform.pojo.Commodity;
import internationalenergytradingplatform.service.ExcelService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class ExcelServiceImpl implements ExcelService {


    /**
     *
     * @author yingfeng
     * @date 2024/3/15 14:33
    读取上传的Excel文件并将其映射到POJO对象列表中
     */
    public List<Commodity> readExcelFile(MultipartFile file) throws IOException {
        String companyId = BaseContext.getCurrentId();//获取公司id
        List<Commodity> excelDataList = new ArrayList<>();
        // 使用Apache POI创建Workbook对象，从上传的文件获取输入流
        Workbook workbook = WorkbookFactory.create(file.getInputStream());
        // 获取第一个工作表
        Sheet sheet = workbook.getSheetAt(0);
        // 获取行迭代器
        Iterator<Row> rowIterator = sheet.iterator();
        // 跳过标题行
        rowIterator.next();
        // 遍历行
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            // 创建Commodity对象并设置属性
            Commodity commodity = new Commodity();
            commodity.setSupplierAccount(companyId);
            commodity.setCommodityStatus(2);
            commodity.setName(row.getCell(0).getStringCellValue());
            commodity.setDescribe(row.getCell(1).getStringCellValue());
            commodity.setParameter(row.getCell(2).getStringCellValue());
            commodity.setPrice(row.getCell(3).getNumericCellValue());
            commodity.setUnitPrice(row.getCell(4).getStringCellValue());
            commodity.setInventory(row.getCell(5).getNumericCellValue());
            commodity.setUnitInventory(row.getCell(6).getStringCellValue());
            commodity.setImage1(row.getCell(7).getStringCellValue());
            commodity.setImage2(row.getCell(8).getStringCellValue());
            commodity.setImage3(row.getCell(9).getStringCellValue());
            commodity.setDetailedImages(row.getCell(10).getStringCellValue());
            commodity.setClassification((int) row.getCell(11).getNumericCellValue());
            // 将Commodity对象添加到列表中
            excelDataList.add(commodity);
        }
        // 关闭Workbook对象，释放资源
        workbook.close();
        return excelDataList;
    }
}
